namespace Brjnk.Maps.Downloader
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// </summary>
    public class Downloader
    {
        IDownloadLogger logger;
        IOverloadProtection overloadProtection;
        DownloadScheduler scheduler;
        int threadsCount;

        DownloadThread[] threads;

        public Downloader(int threadsCount,  IDownloadLogger logger, IOverloadProtection  overloadProtection)
        {
            if (threadsCount <= 0) throw new ArgumentOutOfRangeException("threadsCount");
            this.threadsCount = threadsCount;
            this.logger = logger;
            this.overloadProtection = overloadProtection;
            this.scheduler = new DownloadScheduler(overloadProtection);
            CreateThreads();
            overloadProtection.Initialize(threads);
        }

        private void CreateThreads()
        {
            threads = new DownloadThread[threadsCount];
            for (int i = 0; i < threadsCount; i++)
            {
                threads[i] = new DownloadThread(scheduler, logger);
            }
        }

        public DownloadTask Download(Uri uri, DownloadTaskPriority priority)
        {
            DownloadTaskUpdater updater;
            var task = new DownloadTask(uri, priority, out updater);
            scheduler.Add(new DownloadTaskWithUpdater(task, updater));
            for (int i = 0; i < threadsCount; i++) 
                threads[i].Continue();
            
            return task;

        }

        public void Abort()
        {
            foreach (var thread in threads)
                thread.Abort();
        }
    }
}
